/*Really Simple Reader - An RSS feed reader for Android*/
/*       Created by B. Gokulakrishnan - 080125J        */
/* 		 	 CS3200 - Programming Project			   */

package uit.cinemainfo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/*
 *This class creates the ReallySimple reader Activity (which displays the main screen) and uses methods
 *to obtain and parse XML data from the given RSS feed.
 */

public class ListNewsActivity extends Activity {

	static RSSObject selectedItem = null;
	static String RSSTitle;
	static String feedUrl;
	static File openedFileName;	
	boolean wena = false;

	String url_vi = "http://giaitri.vnexpress.net/rss/phim.rss";
	String url = "http://news.yahoo.com/rss/movies";
	File f;

	TextView tv;
	ListView rssView;
	ArrayList<RSSObject> rSSObjects = new ArrayList<RSSObject>();
	ArrayList<RSSObject> newItems;
	ArrayAdapter<RSSObject> aa;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_news);
		
		if (android.os.Build.VERSION.SDK_INT > 9) {
		      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		      StrictMode.setThreadPolicy(policy);
		    }
		
		newItems = getRSSItems(connect());		
		

		rssView = (ListView) findViewById(R.id.rssListView);

		aa = new ArrayAdapter<RSSObject>(this, R.layout.item, rSSObjects);
		rssView.setAdapter(aa);
		rSSObjects.clear();
		rSSObjects.addAll(newItems);
		aa.notifyDataSetChanged();

		rssView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> av, View view, int index,
					long arg3) {
				selectedItem = rSSObjects.get(index);

				Intent intent = new Intent(ListNewsActivity.this,DetailNewsActivity.class);
				startActivity(intent);
			}
		});

		

	}
	/*
	 *This method is a DOM-based XML parser engine which processes the remote XML data stream , 
	 *breaks it into elements, categorises each element according to its XML tag and stores the 
	 *completely built element structure to an ArrayList.
	 */

	public ArrayList<RSSObject> getRSSItems(InputStream s) {

		ArrayList<RSSObject> rSSObjects = new ArrayList<RSSObject>();

		try {

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();

			Document document = db.parse(s);
			Element element = document.getDocumentElement();

			NodeList nodeList = element.getElementsByTagName("item");

			if (nodeList.getLength() > 0) {
				for (int i = 0; i < nodeList.getLength(); i++) {

					Element currentElement = (Element) nodeList.item(i);

					Element _titleE = (Element) currentElement
							.getElementsByTagName("title").item(0);
					Element _descriptionE = (Element) currentElement
							.getElementsByTagName("description").item(0);
					Element _pubDateE = (Element) currentElement
							.getElementsByTagName("pubDate").item(0);
					Element _linkE = (Element) currentElement
							.getElementsByTagName("link").item(0);

					String _title = _titleE.getFirstChild().getNodeValue();
					String _description = _descriptionE.getFirstChild()
							.getNodeValue();
					Date _pubDate = new Date(_pubDateE.getFirstChild()
							.getNodeValue());
					String _link = _linkE.getFirstChild().getNodeValue();

					RSSObject rSSObject = new RSSObject(_title, _description,
							_pubDate, _link);

					rSSObjects.add(rSSObject);
				}
			}

		} catch (Exception e) {
			//"The URL you provided is not valid. Please check and try again."
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder
					.setMessage(e.getMessage())
					.setCancelable(false).setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									ListNewsActivity.this.finish();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
		}

		return rSSObjects;

	}
	
	/*
	 * This method creates an HTTP connection with the remote RSS host pointed by the user-specified
	 * URL and returns the server's response as a stream of XML data.
	 */
	public InputStream connect() {

		try {

			URL Url = new URL(this.url);
			if(ListNewsActivity.this.getResources().getConfiguration().locale.getLanguage().equals("vi")){
				Url = new URL(this.url_vi);
			}
			//RSSTitle = url.getHost();
			//tv = (TextView) findViewById(R.id.label);
			//tv.setText(RSSTitle);

			HttpURLConnection conn = (HttpURLConnection) Url.openConnection();

			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream is = conn.getInputStream();
				this.wena = true;
				return is;
			} else {
				return null;
			}
		}catch(IOException e){
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_list_news, menu);
		return true;
	}
	
	public boolean onPrepareOptionsMenu(Menu menu){
		MenuItem item = menu.findItem(R.id.menu_news);
		item.setEnabled(false);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.menu_showing:
	        	StartShowing();
	            return true;
	        case R.id.menu_coming:
	        	StartComing();
	            return true;
	        case R.id.menu_theater:
	        	StartTheater();
	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	public void StartComing(){
		Intent intent = new Intent(ListNewsActivity.this, ComingActivity.class);
		startActivity(intent);
	}
	
	public void StartShowing(){
		Intent intent = new Intent(ListNewsActivity.this, ShowingActivity.class);
		startActivity(intent);
	}
	
	public void StartTheater(){
		Intent intent = new Intent(ListNewsActivity.this, TheaterActivity.class);
		startActivity(intent);
	}
}